package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import Models.StockCode;

public class StockCodePresenter extends AbstractPresenter<StockCode> {
	final String SINGLEITEM = "stockCode";
	final String MULTIITEM = "stockCodes";
	
	public ArrayList<StockCode> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public StockCode tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public StockCode createItemFromJSONObject(JSONObject jsonObj){
		StockCode stockCode = new StockCode();
		try{
			stockCode.setStockID(jsonObj.getInt("stockID"));
			stockCode.setTableID(jsonObj.getInt("tableID"));
			//Build Warehouse
			WarehousePresenter whPresenter = new WarehousePresenter();
			JSONObject jsonWG = jsonObj.getJSONObject("whid");
			stockCode.setWearhouseID(whPresenter.createItemFromJSONObject(jsonWG));
			if(!jsonObj.isNull("stockVendID")){
				//create discount if set
				VendorPresenter vendorPresenter = new VendorPresenter();
				JSONObject jsonItem = jsonObj.getJSONObject("stockVendID");
				stockCode.setVendorID(vendorPresenter.createItemFromJSONObject(jsonItem));
			} else {
				stockCode.setVendorID(null);
			}
			if(!jsonObj.isNull("stockAltVendID")){
				//create discount if set
				VendorPresenter vendorPresenter = new VendorPresenter();
				JSONObject jsonItem = jsonObj.getJSONObject("stockAltVendID");
				stockCode.setAltVendorID(vendorPresenter.createItemFromJSONObject(jsonItem));
			} else {
				stockCode.setAltVendorID(null);
			}
			return stockCode;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(StockCode item){
		try{
			JSONObject json = new JSONObject();
			json.put("stockID", item.getStockID());
			json.put("tableID", item.getTableID());
			WarehousePresenter whPresenter = new WarehousePresenter();
			json.put("whid", whPresenter.createJSON(item.getWearhouseID()));
			if(item.getVendorID()!=null){
				final VendorPresenter vendorPresenter = new VendorPresenter();
				json.put("stockVendID", vendorPresenter.createJSON(item.getVendorID()));
			} else {
				json.put("stockVendID", JSONObject.NULL);
			}
			if(item.getAltVendorID()!=null){
				final VendorPresenter vendorPresenter = new VendorPresenter();
				json.put("stockAltVendID", vendorPresenter.createJSON(item.getAltVendorID()));
			} else {
				json.put("stockAltVendID", JSONObject.NULL);
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public StockCode getEmptyEntity(){
		StockCode entity = new StockCode();
		return entity;
	}
}
